package com.example.myapplication.GaojiActivity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.myapplication.R

class PageOneActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_page_one)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        // 1. 获取到按钮
        val btn = findViewById<View>(R.id.btn_action_next)
        btn.setOnClickListener {
            // 2. 创建 Intent 并指定目标 Activity
            // 这段代码的作用是创建一个新的Intent(意图)对象，跳转到PageTwoActivity页面
            // this表示当前Activity上下文
            // PageTwoActivity::class.java表示要跳转的目标Activity类
            val intent = Intent(this, PageTwoActivity::class.java)

            // 3. 添加附加数据
            intent.putExtra("user_name", "李四")
            intent.putExtra("user_age", 25)

            // 4. 启动Activity跳转
            startActivity(Intent(intent))
        }
        // 2. 带返回结果的跳转
        // 使用新版 Activity Result API（推荐）
        // 注册一个Activity结果监听器，用于处理从PageTwoActivity返回的结果
        // 当PageTwoActivity返回RESULT_OK时，获取名为"result_data"的字符串数据
        val resultLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data?.getStringExtra("result_data")
                Toast.makeText(this, "返回数据: $data", Toast.LENGTH_SHORT).show()
            }
        }

        findViewById<Button>(R.id.btn_get_result).setOnClickListener {
            val intent = Intent(this, PageTwoActivity::class.java)
            resultLauncher.launch(intent)
        }
    }
}